﻿//
// Copyright (c) 2010
// by Chris Paterra
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using DotNetNuke.ContentLibrary.Components.Common;
using DotNetNuke.ContentLibrary.Components.Entities;
using DotNetNuke.ContentLibrary.Components.WebControls;
using Telerik.Web.UI;

namespace DotNetNuke.ContentLibrary.Components.Templates {

	#region Layout Template

	public class CommentLayoutTemplate : ITemplate {

		private readonly int _pageSize;
		private readonly Unit _width;
		private readonly ControlBehavior.PagerPlacementMode _pagerPlacement;

		public CommentLayoutTemplate(int pageSize, Unit width, ControlBehavior.PagerPlacementMode pagerPlacement)
		{
			_pageSize = pageSize;
			_width = width;
			_pagerPlacement = pagerPlacement;
		}

		public void InstantiateIn(Control container)
		{
			//top pager
			if (_pagerPlacement == ControlBehavior.PagerPlacementMode.Top || _pagerPlacement == ControlBehavior.PagerPlacementMode.TopAndBottom)
			{
				var divTopContainer = new HtmlGenericControl("div");
				CreatePager(divTopContainer, "Top");
				container.Controls.Add(divTopContainer);
			}

			// middle content area
			var placeHolder = new PlaceHolder { ID = "itemPlaceholder" };
			container.Controls.Add(placeHolder);

			// bottom pager
			if (_pagerPlacement != ControlBehavior.PagerPlacementMode.Bottom &&
			    _pagerPlacement != ControlBehavior.PagerPlacementMode.TopAndBottom) return;
			var divBottomContainer = new HtmlGenericControl("div");
			CreatePager(divBottomContainer, "Bottom");
			container.Controls.Add(divBottomContainer);
		}

		/// <summary>
		/// Creates a data pager.
		/// </summary>
		/// <param name="divContainer"></param>
		/// <param name="suffix"></param>
		private void CreatePager(Control divContainer, string suffix) {
			var topDataPager = new DnnDataPager
			{
				ID = "dnnDataPager" + suffix,
				PageSize = _pageSize,
				Width = _width
			};

			var firstPrevPager = new RadDataPagerButtonField { FieldType = PagerButtonFieldType.FirstPrev };
			topDataPager.Fields.Add(firstPrevPager);

			var numericPager = new RadDataPagerButtonField { FieldType = PagerButtonFieldType.Numeric };
			topDataPager.Fields.Add(numericPager);

			var nextLastPager = new RadDataPagerButtonField { FieldType = PagerButtonFieldType.NextLast };
			topDataPager.Fields.Add(nextLastPager);

			divContainer.Controls.Add(topDataPager);
		}

	}

	#endregion

	public class Comment : ITemplate
	{
		private readonly int _currentUserID;
		readonly ListItemType _templateType;
		private readonly int _portalID;
		private readonly bool _isModerator;
		private readonly string _sharedResourceFile;
		private readonly bool _enableRating;

		public Comment(ListItemType type, int currentUserID, int portalID, bool isModerator, string sharedResourceFile, bool enableRating)
		{
			_templateType = type;
			_currentUserID = currentUserID;
			_portalID = portalID;
			_isModerator = isModerator;
			_sharedResourceFile = sharedResourceFile;
			_enableRating = enableRating;
		}

		public void InstantiateIn(Control container)
		{
			var divContainer = new HtmlGenericControl("div");
			var divModButtons = new HtmlGenericControl("div");
			var divCreatedInfo = new HtmlGenericControl("div");
			var divEngage = new HtmlGenericControl("div");
			//var headTitle = new HtmlGenericControl("h3");
			var imgUser = new DnnBinaryImage();
			var hlUser = new HyperLink();
			var lblCreatedOnDate = new Label();
			var imgEdit = new ImageButton();
			var imgDelete = new ImageButton();
			var imgApprove = new ImageButton();
			var body = new Literal();
			var lnkReply = new LinkButton();
			var commentRating = new UserRating();

			switch (_templateType) {
				case ListItemType.Item:
					divContainer.Attributes["class"] = "item-wrapper";

					//headTitle.ID = "headTitle";
					//divContainer.Controls.Add(headTitle);
	
					imgUser.ID = "imgUser";
					imgUser.Height = 60;
					imgUser.Width = 60;
					divContainer.Controls.Add(imgUser);
					

					hlUser.ID = "hlUser";
					//hlUser.CssClass = "CommandButton";
					divCreatedInfo.Controls.Add(hlUser);
					
					lblCreatedOnDate.ID = "lblCreatedOnDate";
					//lblCreatedOnDate.CssClass = "date";
					divCreatedInfo.Controls.Add(lblCreatedOnDate);
					divContainer.Controls.Add(divCreatedInfo); // </div>

					body.ID = "body";
					divContainer.Controls.Add(body);

					if (_isModerator)
					{
						divModButtons.Attributes["class"] = "mod-buttons";

						imgEdit.ImageUrl = "~/images/edit.gif";
						imgEdit.ID = "imgEdit";
						imgEdit.CommandName = "Select";
                        imgEdit.ToolTip = Services.Localization.Localization.GetString("Edit", _sharedResourceFile);
						imgEdit.CausesValidation = false;
						imgEdit.Attributes.Add("onClick", @"javascript:window.location.hash = ""#commentinput"";");
						divModButtons.Controls.Add(imgEdit);

						imgDelete.ImageUrl = "~/images/delete.gif";
						imgDelete.ID = "imgDelete";
						imgDelete.CommandName = "DeleteItem";
                        imgDelete.ToolTip = Services.Localization.Localization.GetString("Delete", _sharedResourceFile);
						imgDelete.CausesValidation = false;
                        imgDelete.Attributes.Add("onClick", "javascript:return confirm('" + Services.Localization.Localization.GetString("DeleteItem") + "');");
						divModButtons.Controls.Add(imgDelete);

						imgApprove.ImageUrl = "~/DesktopModules/ContentLibrary/images/approve.png";
						imgApprove.ID = "imgApprove";
						imgApprove.CommandName = "Approve";
                        imgApprove.ToolTip = Services.Localization.Localization.GetString("Approve", _sharedResourceFile);
						imgApprove.CausesValidation = false;
						divModButtons.Controls.Add(imgApprove);

						divContainer.Controls.Add(divModButtons);
					}

					if (_currentUserID > 0)
					{
						lnkReply.ID = "lnkReply";
						lnkReply.CommandName = "Reply";
						lnkReply.CssClass = "CommandButton";
                        lnkReply.Text = Services.Localization.Localization.GetString("Reply", _sharedResourceFile);
						lnkReply.CausesValidation = false;
						lnkReply.Attributes.Add("onClick", @"javascript:window.location.hash = ""#commentinput"";");
						divEngage.Controls.Add(lnkReply);
					}

					if (_enableRating)
					{
						commentRating.ID = "UserRating";
						commentRating.ChildType = "Comment";
						commentRating.RatingMode = ControlBehavior.RatingControlMode.Thumbs;
						commentRating.CurrentUserID = _currentUserID;
						commentRating.PortalID = _portalID;
						divEngage.Controls.Add(commentRating);
					}
					
					divContainer.Controls.Add(divEngage);
					divContainer.DataBinding += DataBinding;
					break;
				case ListItemType.AlternatingItem:
					divContainer.Attributes["class"] = "alt-item-wrapper";

					//headTitle.ID = "headTitle";
					//divContainer.Controls.Add(headTitle);
	
					imgUser.ID = "imgUser";
					imgUser.Height = 60;
					imgUser.Width = 60;
					divContainer.Controls.Add(imgUser);
					
					hlUser.ID = "hlUser";
					//hlUser.CssClass = "CommandButton";
					divCreatedInfo.Controls.Add(hlUser);
					
					lblCreatedOnDate.ID = "lblCreatedOnDate";
					//lblCreatedOnDate.CssClass = "date";
					divCreatedInfo.Controls.Add(lblCreatedOnDate);
					divContainer.Controls.Add(divCreatedInfo); // </div>

					body.ID = "body";
					divContainer.Controls.Add(body);

					if (_isModerator) {
						divModButtons.Attributes["class"] = "mod-buttons";

						imgEdit.ImageUrl = "~/images/edit.gif";
						imgEdit.ID = "imgEdit";
						imgEdit.CommandName = "Select";
                        imgEdit.ToolTip = Services.Localization.Localization.GetString("Edit", _sharedResourceFile);
						imgEdit.CausesValidation = false;
						imgEdit.Attributes.Add("onClick", @"javascript:window.location.hash = ""#commentinput"";");
						divModButtons.Controls.Add(imgEdit);

						imgDelete.ImageUrl = "~/images/delete.gif";
						imgDelete.ID = "imgDelete";
						imgDelete.CommandName = "DeleteItem";
                        imgDelete.ToolTip = Services.Localization.Localization.GetString("Delete", _sharedResourceFile);
						imgDelete.CausesValidation = false;
                        imgDelete.Attributes.Add("onClick", "javascript:return confirm('" + Services.Localization.Localization.GetString("DeleteItem") + "');");
						divModButtons.Controls.Add(imgDelete);

						imgApprove.ImageUrl = "~/DesktopModules/ContentLibrary/images/approve.png";
						imgApprove.ID = "imgApprove";
						imgApprove.CommandName = "Approve";
                        imgApprove.ToolTip = Services.Localization.Localization.GetString("Approve", _sharedResourceFile);
						imgApprove.CausesValidation = false;
						divModButtons.Controls.Add(imgApprove);

						divContainer.Controls.Add(divModButtons);
					}
					
					if (_currentUserID > 0) {
						lnkReply.ID = "lnkReply";
						lnkReply.CommandName = "Reply";
						lnkReply.CssClass = "CommandButton";
                        lnkReply.Text = Services.Localization.Localization.GetString("Reply", _sharedResourceFile);
						lnkReply.CausesValidation = false;
						lnkReply.Attributes.Add("onClick", @"javascript:window.location.hash = ""#commentinput"";");
						divEngage.Controls.Add(lnkReply);
					}

					if (_enableRating) {
						commentRating.ID = "UserRating";
						commentRating.ChildType = "Comment";
						commentRating.RatingMode = ControlBehavior.RatingControlMode.Thumbs;
						commentRating.CurrentUserID = _currentUserID;
						commentRating.PortalID = _portalID;
						divEngage.Controls.Add(commentRating);
					}

					divContainer.Controls.Add(divEngage);
					divContainer.DataBinding += DataBinding;
					break;
			}

			container.Controls.Add(divContainer);
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		public void DataBinding(object sender, EventArgs e) {
			var container = (HtmlGenericControl)sender;
			var dataItem = ((RadListViewDataItem)container.NamingContainer).DataItem;
			var objComment = (CommentInfo)dataItem;
		
			//var headTitle = (HtmlGenericControl) container.FindControl("headTitle");
			//headTitle.InnerText = objComment.Title;

			var imgUser = (DnnBinaryImage)container.FindControl("imgUser");
			imgUser.ImageUrl = container.Parent.ResolveUrl("~/images/no_avatar.gif");

			var hlUser = (HyperLink)container.FindControl("hlUser");
			hlUser.Text = objComment.DisplayName;
			hlUser.NavigateUrl = DotNetNuke.Common.Globals.UserProfileURL(objComment.CreatedByUserID);

			var lblCreatedOnDate = (Label)container.FindControl("lblCreatedOnDate");
			lblCreatedOnDate.Text = objComment.CreatedOnDate.ToShortDateString();

			if (_isModerator)
			{
				var imgEdit = (ImageButton)container.FindControl("imgEdit");
				imgEdit.CommandArgument = objComment.CommentID.ToString();

				var imgDelete = (ImageButton)container.FindControl("imgDelete");
				imgDelete.CommandArgument = objComment.CommentID.ToString();

				var imgApprove = (ImageButton)container.FindControl("imgApprove");
				if (objComment.Approved) {
					imgApprove.Visible = false;
				} else {
					imgApprove.CommandArgument = objComment.CommentID.ToString();
					imgApprove.Visible = true;
				}
			}

			if (_currentUserID > 0)
			{
				var lnkReply = (LinkButton)container.FindControl("lnkReply");
				lnkReply.CommandArgument = objComment.CommentID.ToString();
			}

			var body = (Literal)container.FindControl("body");
			body.Text = @"<p>" +  HttpContext.Current.Server.HtmlDecode(objComment.Comment) + @"</p>";

			if (objComment.ContentItemID <= 0) return;
			if (_enableRating)
			{
				var userRating = (UserRating)container.FindControl("UserRating");
				userRating.ChildKeyID = objComment.CommentID;
				userRating.CurrentContentItemID = objComment.ContentItemID;
			}
			
		}

	}

}